package cn.aylog.test;

import cn.aylog.service.UserService;
import cn.aylog.service.impl.UserServiceImpl;
import org.junit.Test;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyDemo {

    @Test
    public void run1() {
        UserServiceImpl serviceImpl = new UserServiceImpl();

        UserService service = (UserService)Proxy.newProxyInstance(serviceImpl.getClass().getClassLoader(), UserServiceImpl.class.getInterfaces(), (o, method, objects) -> {
            System.out.println("before...");
            Object ret = method.invoke(serviceImpl, objects);
            System.out.println("after...");
            return ret;
        });

        service.selectAll();
    }

    @Test
    public void run2() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(UserServiceImpl.class);
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("before...");
                Object ret = methodProxy.invokeSuper(o, objects);
                System.out.println("after...");
                return ret;
            }
        });
        UserServiceImpl o = (UserServiceImpl)enhancer.create();
        o.selectAll();
    }

}
